// 检查登录状态
async function checkLogin() {
    const token = localStorage.getItem('token');
    if (token) {
        try {
            const res = await axios.get('/api/users/current', {
                headers: { 'Authorization': token }
            });
            if (res.data.code === 200) {
                const username = document.getElementById('username');
                const logout = document.getElementById('logout');
                const login = document.getElementById('login');
                const register = document.getElementById('register');
                
                if (username) username.textContent = res.data.data.username;
                if (logout) logout.style.display = 'inline';
                if (login) login.style.display = 'none';
                if (register) register.style.display = 'none';
                
                return true;
            } else {
                localStorage.removeItem('token');
                showLoginButtons();
                return false;
            }
        } catch (error) {
            console.error('获取用户信息失败:', error);
            localStorage.removeItem('token');
            showLoginButtons();
            return false;
        }
    } else {
        showLoginButtons();
        return false;
    }
}

// 显示登录按钮
function showLoginButtons() {
    const username = document.getElementById('username');
    const logout = document.getElementById('logout');
    const login = document.getElementById('login');
    const register = document.getElementById('register');
    
    if (username) username.textContent = '';
    if (logout) logout.style.display = 'none';
    if (login) login.style.display = 'inline';
    if (register) register.style.display = 'inline';
}

// 退出登录
function handleLogout() {
    localStorage.removeItem('token');
    showLoginButtons();
    layer.msg('退出成功');
}

// 格式化日期
function formatDate(date) {
    return new Date(date).toLocaleString();
}

// 显示提示信息
function showMessage(message, type = 'info') {
    layer.msg(message, {
        icon: type === 'success' ? 1 : type === 'error' ? 2 : 0
    });
}

// 显示确认对话框
function showConfirm(message, callback) {
    layer.confirm(message, {
        btn: ['确定', '取消']
    }, function() {
        callback(true);
    }, function() {
        callback(false);
    });
}

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 检查登录状态
    checkLogin();
    
    // 绑定退出按钮事件
    const logoutBtn = document.getElementById('logout');
    if (logoutBtn) {
        logoutBtn.addEventListener('click', handleLogout);
    }
}); 